<?php 
namespace ListMenu\Model;

 use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Predicate\In;
	
 class ListMenuTable
 {
     protected $tableGateway;

     public function __construct(TableGateway $tableGateway)
     {
         $this->tableGateway = $tableGateway;
     }

     public function fetchAll()
     {
         $select = $this->tableGateway->getSql()->select()->order ( array (
				'ID_M DESC' 
		) );
         $resultSet = $this->tableGateway->selectWith ( $select );
         $resultSet->buffer ();
         return $resultSet;
     }
     
     public function countMenu(){
     	return $this->tableGateway->select()->count();
     }
     
     public function saveListMenu(ListMenu $menus,$id)
     {
     	if($menus->activemenu == null)
     		$menus->activemenu = 0;
     	if(isset($menus->menus )){
	     	$data = array(
	     			'TYPE_M' => $menus->select_menu ,
	     			'LABEL_M' => $menus->name_menu ,
	     			'ROUTE_M' => $menus->router_menu ,
	     			'ACTIVE_M' => $menus->activemenu ,
	     			'ID_SUB_M' => $menus->menus ,
	     			'ISSUB_M' => '0' ,
	     	);
	     	$this->tableGateway->update(array('ISSUB_M'=>'1'), array('ID_M' => $menus->menus));
     	} else 
	     		$data = array(
	     				'TYPE_M' => $menus->select_menu ,
	     				'LABEL_M' => $menus->name_menu ,
	     				'ROUTE_M' => $menus->router_menu ,
	     				'ACTIVE_M' => $menus->activemenu ,
	     				'ISSUB_M' => '0' ,
	     		);
     
     	if ($id == 0) {
     		$this->tableGateway->insert($data);
     	}else {
     		if ($this->getMenu($id)) {
     			$this->tableGateway->update($data, array('ID_M' => $id));
     			if($this->getSubMenu($menus->hidden_menu) == false)
     				$this->tableGateway->update(array('ISSUB_M'=>'0'), array('ID_M' => $menus->hidden_menu));
     		} else {
     			throw new \Exception('Product id does not exist');
     		}
     	}
     }
     
     public function getMenu($id)
     {
     	$id  = (int) $id;
     	$rowset = $this->tableGateway->select(array('ID_M' => $id));
     	$row = $rowset->current();
     	if ($row) {
     		$row->select_menu = $row->TYPE_M;
     		$row->name_menu = $row->LABEL_M;
     		$row->router_menu = $row->ROUTE_M;
     		$row->activemenu = $row->ACTIVE_M;
     		$row->menus = $row->ID_SUB_M;
     		$row->hidden_menu = $row->ID_SUB_M;
     	}
     	return $row;
     }
     
     public function getSubMenu($id)
     {
     	$id  = (int) $id;
     	$rowset = $this->tableGateway->select(array('ID_SUB_M' => $id));
     	$row = $rowset->current();
     	return $row;
     }
     
     public function deleteMenu($id)
     {
     	$this->tableGateway->delete(array('ID_M' => (int) $id));
     }
 }